#include "config.h"

#include <clx/libECM.h>

#include "ms2sim.h"

ECMBOOL	going_to_shutdown;

static ECMBOOL	stopping;

static ecm_mutex_t	mutex;
static ecm_cond_t	cond;

static void
progress_func(ecm_ptr_t ctx)
{
	ecm_uint64	last_tick = ecm_tickcount();
	ecm_uint64	ts_max = (ecm_uint64)duration * USEC_MAX;

	ecm_mutex_lock(mutex);

	while (!going_to_shutdown && !stopping) {
		ecm_uint32	timeout = 10000;

		ecm_cond_wait(cond, mutex, &timeout);
		if (!going_to_shutdown && !stopping) {
			ecm_uint64	cur_tick = ecm_tickcount();
			if (cur_tick - last_tick >= 10000) {
				ECMVERBOSE("Progress: %.1lf%%", (100.0 * ts_subsys) / ts_max);
				last_tick = cur_tick;
			}
		}
	}

	ecm_mutex_unlock(mutex);
}

void
runsim(void)
{
	ecm_thread_t	progress_reporter;

	if (!setup_logging()) {
		ERR("setup_logging() failed");
		return;
	}

	mutex = ecm_mutex_create(ECM_FALSE);
	cond = ecm_cond_create();

	ecm_thread_create(&progress_reporter, progress_func, NULL);

	run_sub_systems();

	ecm_mutex_lock(mutex);
	stopping = ECM_TRUE;
	ecm_cond_signal(cond);
	ecm_mutex_unlock(mutex);

	ecm_thread_free(progress_reporter);

	if (!going_to_shutdown)
		ECMVERBOSE("Simulation Completed\n");

	bcache_op->fini();

	cleanup_logging();
}
